
const app = getApp()
const config = require('../../config.js');
var interval = null
var intervalimg = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperCurrent: 0,
  },
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    clearInterval(intervalimg);
    var _this = this;
    _this.setData({
      inputOrderNumberValue: ""
    })
    interval = setInterval(function () {
      if (app.loadComplete) {
        _this.setData({
          userInfo: app.userInfo,
          loginUser: app.loginUser,
          companyName: app.companyInfo.name
        })

        wx.setNavigationBarTitle({
          title: app.appName,
        })

        //最新消息
        wx.request({
          url: config.requestUrl + "news/getNewsList",
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            "code": config.tenantCode
          },
          success: function (res) {

            if (res.data.content.length != 0) {
              var content = res.data.content;
              _this.setData({
                newsArray: content
              })
            }
          },
          fail: function (res) {
          }
        })
        //轮播图片
        wx.request({
          url: config.requestUrl + "advertise/findAdvertiseList",
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            data: '{code:"' + config.tenantCode + '"}'
          },
          success: function (res) {
            var slider = []
            if (res.data.content.length != 0) {
              for (var i = 0; i < res.data.content.length; i++) {
                slider[i] = res.data.content[i].imgUrl
              }
              _this.setData({
                slider: slider
              })
              _this.data.imgs = slider.length;
              intervalimg = setInterval(function () {
                _this.scrollLeft(_this.data.swiperCurrent);
              }, 5000)
            }
          },
          fail: function (res) {
          }
        })

        //货物跟踪查询;
        if (app.loginUser != null) {
          //订单和代收数据
          wx.request({
            url: config.requestUrl + "order/searchOrderForIndex",
            method: "GET",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              code: config.tenantCode,
              userId: app.loginUser.id,
              mobile: app.loginUser.mobile
            },
            success: function (msg) {
              if (Array.isArray(msg.data.content) && msg.data.content.length != 0) {
                _this.setData({
                  orderForIndex: msg.data.content,
                  showView: true
                })
              }
            },
            fail: function (msg) {
            }
          })
        }

        clearInterval(interval)
      }
    }, 1000)
  },
  //扫码
  toScanQRcode() {
    wx.scanCode({
      success: (res) => {
        if (res.result.indexOf(",") == -1) {
          // wx.showToast({
          //   title: "抱歉，该订单状态为未处理",
          //   icon: 'none',
          //   duration: 3000
          // })
          wx.showModal({
            title: '提示',
            content: '抱歉，该运单状态为未受理',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })

          return false
        }

        var values = res.result.split(",");
        var tenantCode = values[0];
        var orderNumber = values[1];

        if (tenantCode == undefined || tenantCode == null || tenantCode == "" || tenantCode == "null") {
          //app.tip("金融代码不存在", "none");
          // wx.showToast({
          //   title: "金融代码不存在",
          //   icon: 'none',
          //   duration: 3000
          // })

          wx.showModal({
            title: '提示',
            content: '金融代码不存在',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })
          return false
        } else {
          if (tenantCode == config.tenantCode) {
            wx.navigateTo({ url: "../freightTrack/freightTrackDetail?dh=" + orderNumber })
          } else {
            //app.tip("抱歉！无法找到该订单，请检查订单号。", "none");
            // wx.showToast({
            //   title: "抱歉, 当前小程序为【" +app.appName+"】，请核实运单！",
            //   icon: 'none',
            //   duration: 3000
            // })
            wx.showModal({
              title: '提示',
              content: "抱歉, 当前小程序为【" + app.appName + "】，请核实运单！",
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                }
              }
            })
            return false
          }
        }
      },
      fail: (res) => {
        wx.showModal({
          title: '提示',
          content: res,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
        return false
      }
    })
  },
  orderNumberInput: function (e) {
    this.setData({
      inputOrderNumberValue: e.detail.value
    })
  },
  //放大镜跳转货物跟踪页
  toFreightTrack: function (e) {
    var orderNumber = this.data.inputOrderNumberValue;
    if (orderNumber == undefined || orderNumber == "") {
      app.tip("运单号不可以为空，请输入运单号", 'none')
    } else {
      this.setData({
        inputOrderNumberValue: ""
      })
      wx.navigateTo({ url: "../freightTrack/freightTrackDetail?dh=" + orderNumber })
    }
  },
  //代收和订单信息的页面跳转
  toFreightTrackDetail: function (e) {
    var orderList = this.data.orderForIndex;
    var content = orderList[e.currentTarget.dataset.id];
    //已处理跳转货物跟踪,未处理跳转修改订单
    if (content.generateFlag == 1) {
      wx.navigateTo({ url: "../order/orderDetail?order=" + JSON.stringify(content.order) })
    } else if (content.generateFlag == 0) {
      wx.navigateTo({ url: "../order/orderDetailEdit?order=" + JSON.stringify(content.order) })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 首页导航：flag（是否验证登录） url（跳转地址）
   */
  navigate(e) {
    var flag = e.currentTarget.dataset.index;
    var url = e.currentTarget.dataset.url;
    var type_b = e.currentTarget.dataset.type;
    if (flag != "0") {
      if (app.loginUser == null || app.loginUser.id == null || app.loginUser.id == '') {
        wx.showModal({
          title: '提示',
          content: '用户未登录',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login'
              })
            } else if (res.cancel) {
              return;
            }
          }
        })
      } else {
        if (type_b == "jj" && app.companyInfo.makeOrderFlag != 1) {
          app.tip("请联系管理员修改下单状态", "none");
          return false;
        }
        wx.navigateTo({ url: url })
      }
    } else {
      if (type_b == "jj" && app.companyInfo.makeOrderFlag != 1) {
        app.tip("请联系管理员修改下单状态", "none");
        return false;
      }
      wx.navigateTo({ url: url })
    }
  },

  toWithdraw: function () {

    //掌上取款条件：已登录并且该VIP用户已认证
    if (app.loginUser == null || app.loginUser.id == null || app.loginUser.id == '') {
      wx.showModal({
        title: '提示',
        content: '用户未登录',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
    } else {
      //makeOrderFlag  下单（0未启用，1启用）
      //withdrawFlag   取款（0未启用，1启用）
      if (app.companyInfo.withdrawFlag != 1) {
        app.tip("请联系管理员修改取款状态", "none");
        return false;
      }

      wx.showLoading({
        title: '加载中',
        mask: true
      })

      wx.request({
        url: config.requestUrl + "/user/getVipInfo",
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          "id": app.loginUser.id
        },
        success: function (res) {
          wx.hideLoading()
          if (res.data.code == "100") {

            var vipUser = res.data.content;

            //重新设置登录用户信息
            app.setLoginUser(vipUser);
            var auditStatus = vipUser.auditStatus;
            var bankList = vipUser.bankList;
            if (bankList != null && bankList.length > 0) {
              for (var i = 0; i < bankList.length; i++) {
                if (app.companyInfo.businessSetting.sameAsDefaultDankFlag) {
                  if (bankList[i].name != app.companyInfo.businessSetting.defaultBank) {
                    app.tip("您未绑定" + app.companyInfo.businessSetting.defaultBank + "呢！", "none");
                    return false;
                  }
                }
              }
            }
            if (bankList == null || bankList.length == 0) {
              wx.showModal({
                title: '提示',
                content: '还没有绑定银行卡呢！请添加银行卡！',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({ url: "../user/addbank/addbank" })
                  }
                }
              })
              // } else if (auditStatus == "0") {
              //   app.tip("抱歉，实名认证等待审核中，通过审核方可使用掌上取款", "none");
              //   return false;
              // } else if (auditStatus == "1") {
              //   wx.navigateTo({ url: "../handheldWithdrawals/withdrawalList/withdrawalList" })
              // } else if (auditStatus == "2") {
              //   wx.showModal({
              //     title: '提示',
              //     content: '抱歉，实名认证审核被驳回，请重新认证！',
              //     success: function (res) {
              //       if (res.confirm) {
              //         wx.navigateTo({ url: "../user/identify/identify" })
              //       }
              //     }
              //   })
              // } else {
              //   wx.showModal({
              //     title: '提示',
              //     content: '请实名制认证！',
              //     success: function (res) {
              //       if (res.confirm) {
              //         wx.navigateTo({ url: "../user/identify/identify" })
              //       }
              //     }
              //   })
            } else {
              wx.navigateTo({ url: "../handheldWithdrawals/withdrawalList/withdrawalList" })
            }
          }
        },
        fail: function ({ errMsg }) {
          app.tip(errMsg, "none");
        }
      })
    }

  },
  //触摸开始事件
  touchstart: function (e) {
    this.data.touchDot = e.touches[0].pageX;
  },
  //触摸移动事件
  touchmove: function (e) {
    let swiperCurrenttemp = e.currentTarget.dataset.swipercurrent;
    let touchMove = e.touches[0].pageX;
    let touchDot = this.data.touchDot;
    let time = this.data.time;
    //向左滑动
    if (touchMove - touchDot <= -40 && time < 10 && !this.data.done) {
      this.data.done = true;
      this.scrollLeft(swiperCurrenttemp);
    }
    //向右滑动
    if (touchMove - touchDot >= 40 && time < 10 && !this.data.done) {
      this.data.done = true;
      this.scrollRight(swiperCurrenttemp);
    }
  },
  //触摸结束事件
  touchend: function (e) {
    clearInterval(this.data.interval);
    this.data.time = 0;
    this.data.done = false;
  },
  /**
   * 左滑
   */
  scrollLeft: function (swiperCurrenttemp){
    if (this.data.imgs > 0){
      if ((swiperCurrenttemp + 1) >= this.data.imgs){
        swiperCurrenttemp = 0;
      }else{
        swiperCurrenttemp += 1;
      }
      this.setData({ swiperCurrent: swiperCurrenttemp, slider: this.data.slider});
    }
  },
  /**
   * 右滑
   */
  scrollRight: function (swiperCurrenttemp){
    if (this.data.imgs > 0) {
      if ((swiperCurrenttemp - 1) < 0) {
        swiperCurrenttemp = this.data.imgs - 1;
      } else {
        swiperCurrenttemp -= 1;
      }
      this.setData({ swiperCurrent: swiperCurrenttemp, slider: this.data.slider });
    }
  }
})